import employeeEnum from "@/constant/employees";

/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
* @description: 扁平数组转树状结构
* @param {arr: Array, pid: String} 
* @return { Array }
*/
export function arrayToTree(arr, pid) {
  const tree = arr.filter((item) => item.pid === pid);
  // console.log(tree);
  tree.forEach((item) => {
    item.children = arrayToTree(arr, item.id);
  });
  return tree;
}

/**
* @description: 将数组中每个元素的中文属性名转为英文属性名
* 转换前的数据格式:
*[
*   {
*       "姓名": "小张",
*       "手机号": "13800000252",
*       "入职日期": 44505,
*       "转正日期": 44892,
*       "工号": "9002",
*       "部门": "总裁办"
*   },
*   { …… }
* ]
* 转换后的数格式
* [
*   {
*       "username": "小张",
*       "mobile": "13800000252",
*       "timeOfEntry": 44505,
*       "correctionTime": 44892,
*       "workNumber": "9002",
*       "departmentName": "总裁办"
*   },
*   { …… }
* ]
* @param {results: Array} (每个属性名都要是中文)
* @return {Array}
*/
export function transExcel(results) {
  const mapInfo = {
    '入职日期': 'timeOfEntry',
    '手机号': 'mobile',
    '姓名': 'username',
    '转正日期': 'correctionTime',
    '工号': 'workNumber',
    '部门': 'departmentName',
    '聘用形式': 'formOfEmployment'
  }

  return results.map(item => {
    const objEn = {}
    const zhKeys = Object.keys(item)
    zhKeys.forEach(zhkey => {
      // 如果是日期格式,要做额外处理
      if (mapInfo[zhkey] === 'timeOfEntry' || mapInfo[zhkey] === 'correctionTime') {
        objEn[mapInfo[zhkey]] = new Date(formatExcelDate(item[zhkey]))
      } else {
        objEn[mapInfo[zhkey]] = item[zhkey]
      }
    })
    return objEn
  })
}

/**
* @description: 把excel文件中的日期格式的内容转回成标准时间
https://blog.csdn.net/qq_15054679/article/details/107712966
* @param {type} 
* @return: 
*/
export function formatExcelDate(numb, format = '/') {
  const time = new Date((numb - 25567) * 24 * 3600000 - 5 * 60 * 1000 - 43 * 1000 - 24 * 3600000 - 8 * 3600000)
  time.setYear(time.getFullYear())
  const year = time.getFullYear() + ''
  const month = time.getMonth() + 1 + ''
  const date = time.getDate() + ''
  if (format && format.length === 1) {
    return year + format + month + format + date
  }
  return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
}

/**
* @description: 将聘用形式的id转为中文
* @param {type} 
* @return: 
*/
export function formatValue(id) {
  // const value = employeeEnum.hireType.find((item) => item.id === id).value;
  // 代码优化
  // 将employeeEnum.hireType转为对象hireType
  const hireType = employeeEnum.hireType.reduce((sum, item) => {
    sum[item.id] = item.value;
    return sum;
  }, {});
  return hireType[id] || "未知";
}

/**
* @description: 把后端返回的数据处理成Export2Excel插件需求的二维数组格式,且表头转为中文
转换前
    [
      {id: '65c2', mobile: '1380000002', username: '管理员'},
      {id: '65c3', mobile: '1380000003', username: '孙财'}
    ]
转换后
    header = ['id', 'mobile', 'username', .....]
    data = [
        ['65c2', '1380000002', '管理员', ....],
        ['65c3', '1380000003', '孙财', ....],
    ]
* @param {type} 
* @return: 
*/
export function transExportExcel(rows) {
  const map = {
    'id': '编号',
    'password': '密码',
    'mobile': '手机号',
    'username': '姓名',
    'timeOfEntry': '入职日期',
    'formOfEmployment': '聘用形式',
    'correctionTime': '转正日期',
    'workNumber': '工号',
    'departmentName': '部门',
    'staffPhoto': '头像地址'
  }
  const enHeader = Object.keys(rows[0])
  const zhHeader = enHeader.map(key => {
    return map[key]
  })
  const data = rows.map(item => {
    return enHeader.map(key => {
      if (key === 'formOfEmployment') {
        return formatValue(item[key])
      } else {
        return item[key]
      }
    })
  })
  return { zhHeader, data }
}